package com.nttuan.service2;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import com.nttuan.model.dao.CategoryDao;
import com.nttuan.model.dao.ContactDao;
import com.nttuan.model.dao.LocationDao;
import com.nttuan.model.dao.TaskDao;
import com.nttuan.model.dao.TrackDao;
import com.nttuan.model.dao.UserDao;
import com.nttuan.model.dao.service.CategoryService;
import com.nttuan.model.dao.service.ContactService;
import com.nttuan.model.dao.service.LocationService;
import com.nttuan.model.dao.service.TaskService;
import com.nttuan.model.dao.service.TrackService;
import com.nttuan.model.dao.service.UserService;
import com.nttuan.model.entity.Contact;
import com.nttuan.model.entity.Notification;
import com.nttuan.model.entity.Task;
import com.nttuan.model.entity.Track;
import com.nttuan.model.entity.User;
import com.nttuan.mycalender.R;
import com.nttuan.util.JSONParser;
import com.nttuan.util.LogSupport;
import com.nttuan.util.Network;
import com.nttuan.util.Support;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by TuanNT on 12/1/2014.
 */
public class GetService extends Service{
    private final String TAG = "GetService";
    private final int DELAY = 5000;

    private Context context;
    private Timer timer;
    private News news;
    private CategoryService categoryService;
    private UserService userService;
    private TaskService taskService;
    private ContactService contactService;
    private LocationService locationService;

    @Override
    public void onCreate() {
        this.context = GetService.this;
        this.categoryService = CategoryDao.getInstance(context);
        this.userService = UserDao.getInstance(context);
        this.taskService = TaskDao.getInstance(context);
        this.contactService = ContactDao.getInstance(context);
        this.locationService = LocationDao.getInstance(context);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        this.timer = new Timer();
        this.news = new News();
        this.timer.scheduleAtFixedRate(news, 0,DELAY);
        Log.d(TAG, "started");
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    class News extends TimerTask{

        @Override
        public void run() {
            Log.d(TAG,"get tick");
            if(!Network.isConnect(context))
                return;
            User me = userService.getMe();
            if(me == null)
                return;
            List<Notification> notification=JSONParser.getNotification(me.getEmail(), LogSupport.slastUpdateServer(context));
        //    List<Notification> notification=JSONParser.getNotification("user1@gmail.com", LogSupport.slastUpdateServer(context));

            for(Notification item:notification )
                switch (item.getAction()){
                    case Track.ACTION_SEND_INVITE:
                        if(receiveInvite(item.getPublicId(), item.getMessage())) {
                            LogSupport.saveUpdateServer(context, item.getLastTime());
                        }
                        break;
                    case Track.ACTION_SEND_ACCEPT:
                        if(receiveAccept(item.getPublicId(), item.getMessage())) {
                            LogSupport.saveUpdateServer(context, item.getLastTime());
                        }
                        break;
                    case Track.ACTION_UPDATE_INVITE:
                        if(receiveUpdateInvite(item.getPublicId(), item.getMessage())) {
                            LogSupport.saveUpdateServer(context, item.getLastTime());
                        }
                        break;
                    case Track.ACTION_DELETE_INVITE:
                        if(deleteTask(item.getPublicId(), item.getMessage())) {
                            LogSupport.saveUpdateServer(context, item.getLastTime());
                        }
                        break;
                }
        }
        private boolean deleteTask(int publicId, String message){
           Task task = taskService.taskByPublicId(publicId);
           if(!task.isActive()) // not attend
               return true;
           if(taskService.active(task.getTaskId(), false)) {
               taskService.updatePublicId(task.getTaskId(),-1);
               saveTrack(task, Track.ACTION_RECEIVE_DELETE_INVITE, message);
               return true;
           }
           return false;
        }
        private boolean receiveUpdateInvite(int publicId, String message){
            Task task= JSONParser.getTask(publicId, Track.ACTION_GET_UPDATE);
            if(task == null)
                return false;
            if(taskService.taskByPublicId(task.getPublicId()) == null){ // invite
                task.setCategory(categoryService.createOrUpDate(task.getCategory()));
                task.setLocation(locationService.crateOrUpdate(task.getLocation()));
                task.setTaskId(taskService.createNewId(task));
                List<Contact> contacts = task.getListContact();
                contacts.add(getContactMe());
                for(Contact contact: contacts){
                    contact.setTask(task);
                    contact.setUser(userService.crateOrUpdate(contact.getUser()));
                    contactService.create(contact);
                }
                saveTrack(task, Track.ACTION_RECEIVE_INVITE, message);
            }else{//update
                Task temp = taskService.taskByPublicId(task.getPublicId());
                if(temp == null)
                    return true;
                temp.setCategory(categoryService.createOrUpDate(task.getCategory()));
                temp.setLocation(locationService.crateOrUpdate(task.getLocation()));
                temp.setStart(task.getStart());
                temp.setEnd(task.getEnd());
                temp.setDuring(task.getDuring());
                temp.setRepeat(task.getRepeat());
                taskService.update(temp);
                if(temp.isActive()) { //attend
                    saveTrack(temp, Track.ACTION_RECEIVE_UPDATE_INVITE, message);
                }
            }
            return true;
        }
        private boolean receiveAccept(int publicId, String message){
            Task updateTask = taskService.taskByPublicId(publicId);
            User user = userService.user(message);
            if(updateTask == null || user == null)
                return true;
            if(contactService.attend(updateTask.getTaskId(), user.getUserId(), true)){
                saveTrack(updateTask, Track.ACTION_RECEIVE_ACCEPT, getString(R.string.message_accept, user.getUserName()));
                return true;
            }
            return false;
        }
        private boolean receiveInvite(int publicId, String message){

            Task task= JSONParser.getTask(publicId, Track.ACTION_GET_INVITE);
            if(task == null)
                return false;
            task.setCategory(categoryService.createOrUpDate(task.getCategory()));
            task.setLocation(locationService.crateOrUpdate(task.getLocation()));
            task.setTaskId(taskService.createNewId(task));
            List<Contact> contacts = task.getListContact();
            contacts.add(getContactMe());
            for(Contact contact: contacts){
                contact.setTask(task);
                contact.setUser(userService.crateOrUpdate(contact.getUser()));
                contactService.create(contact);
            }
            saveTrack(task, Track.ACTION_RECEIVE_INVITE, message);
            return true;
        }
        private void saveTrack(Task task,String action, String message){
            TrackService trackService = TrackDao.getInstance(context);
            Date now = Calendar.getInstance().getTime();
            Track track = new Track();
            track.setActon(action);
            track.setMessage(message);
            track.setCommit(true);
            track.setActive(true);
            track.setLastTime(now);
            track.setTask(task);
            trackService.create(track);
        }
        private Contact getContactMe() {
            Contact me = new Contact();
            me.setUser(userService.getMe());
            me.setContactId(0);
            me.setLeader(false);
            me.setActive(true);
            me.setAttend(false);
            return me;
        }
    }

}
